import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';

class CJHive {
  static String _name = "jtyd_hive";
  static CJHive _cjHive = CJHive();
  static CJHive get shared => _cjHive;

  Box? _box;
  bool isOpen() => _box?.isOpen ?? false;

  Future<void> openBox() async {
    _box = await Hive.openBox(_name);
  }

  Future<void> close() async => _box?.close();
}

// 增删改查
extension UseOperation on CJHive {
  Future<void> put(dynamic key, dynamic value) =>
      _box?.put(key, value) ?? Future.value();
  Future<void> putAll(Map<dynamic, dynamic> entries) =>
      _box?.putAll(entries) ?? Future.value();
  Future<void> delete(dynamic key) => _box?.delete(key) ?? Future.value();
  Future<void> deleteAll(Iterable<dynamic> keys) =>
      _box?.deleteAll(keys) ?? Future.value();
  dynamic get(dynamic key, {dynamic defaultValue}) =>
      _box?.get(key, defaultValue: defaultValue) ?? defaultValue;
}

//获取box信息
extension BoxInfo on CJHive {
  Iterable? get values => _box?.values;
  Iterable? get keys => _box?.keys;
  int get length => _box?.length ?? 0;
  bool containsKey(dynamic key) => _box?.containsKey(key) ?? false;
  Map<dynamic, dynamic> toMap() => _box?.toMap() ?? {};
  Iterable? valuesBetween({dynamic startKey, dynamic endKey}) =>
      _box?.valuesBetween(startKey: startKey, endKey: endKey);
}
